package vc.learn.springcloud.controller;

import com.google.common.collect.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.*;
import rx.Observable;
import rx.Observer;
import vc.learn.springcloud.dto.User;
import vc.learn.springcloud.service.AggregationService;

import java.util.HashMap;


/**
 * Created on 2018-08-18 下午4:30.
 *
 * @author <a href="mailto:xiaolei.fu@hotmail.com">xiaolei.fu</a>
 * @version 0.0.1
 * @since 0.0.1
 */
@Slf4j
@RestController
public class AggregationController {
    @Autowired
    private AggregationService aggregationService;


    @GetMapping("/aggregate/{id}")
    public DeferredResult<HashMap<String, User>> aggregate(@PathVariable Long id) {
        Observable<HashMap<String, User>> hashMapObservable = this.aggregateObservable(id);
        return toDeferredResult(hashMapObservable);
    }

    public DeferredResult<HashMap<String,User>> toDeferredResult(Observable<HashMap<String, User>> detail){
        DeferredResult<HashMap<String,User>> result = new DeferredResult<>();
        detail.subscribe(new Observer<HashMap<String, User>>(){

            @Override
            public void onCompleted() {
                log.info("完成。。。");
            }

            @Override
            public void onError(Throwable e) {
                log.info("发生错误。。。",e);
            }

            @Override
            public void onNext(HashMap<String, User> stringUserHashMap) {
                result.setResult(stringUserHashMap);
            }
        });
        return result;
    }



    public Observable<HashMap<String, User>> aggregateObservable(Long id) {
        return Observable.zip(this.aggregationService.getUserById(id), this.aggregationService.getMovieByUser(id),
                (user, movieUser) -> {
                    HashMap<String, User> objectObjectHashMap = Maps.newHashMap();
                    objectObjectHashMap.put("user", user);
                    objectObjectHashMap.put("movieUser", movieUser);
                    return objectObjectHashMap;
                });
    }


}
